<!-- 创建一个HTML文件(index.html),将以下代码复制进去即可运行 -->
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>坦克大战 - 双人协作</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 20px auto;
            background-color: black;
        }
        .instructions {
            text-align: center;
            margin: 10px;
            color: #333;
        }
        .game-info {
            text-align: center;
            margin: 10px;
            font-size: 20px;
            color: #333;
            display: flex;
            justify-content: center;
            gap: 40px;
        }
        .game-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .player-info {
            padding: 10px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-info">
            <div class="player-info">
                <span>得分: <span id="score">0</span></span>
            </div>
            <div class="player-info">
                <span>玩家1生命值: <span id="health1">100</span></span>
            </div>
            <div class="player-info">
                <span>玩家2生命值: <span id="health2">100</span></span>
            </div>
        </div>
        <canvas id="gameCanvas" width="800" height="600"></canvas>
        <div class="instructions">
            <h2>坦克大战 - 双人协作模式</h2>
            <p>玩家1（蓝色）：方向键移动，回车键发射子弹</p>
            <p>玩家2（绿色）：WASD移动，空格键发射子弹</p>
            <p>合作消灭红色敌方坦克获得分数</p>
            <p>注意躲避敌方坦克的子弹!</p>
        </div>
    </div>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');

        class Tank {
            constructor(x, y, color, controls, isEnemy = false) {
                this.x = x;
                this.y = y;
                this.width = 40;
                this.height = 40;
                this.color = color;
                this.speed = isEnemy ? 1 : 2;
                this.bullets = [];
                this.health = 100;
                this.shootCooldown = 0;
                this.direction = { x: 0, y: isEnemy ? 1 : -1 };
                this.controls = controls;
                this.isEnemy = isEnemy;
            }

            moveInDirection(dx, dy) {
                if (dx !== 0 && dy !== 0) {
                    dy = 0;
                }

                if (dx !== 0) {
                    const newX = this.x + dx * this.speed;
                    if (newX >= 0 && newX <= canvas.width - this.width) {
                        this.x = newX;
                    }
                    this.direction = { x: dx, y: 0 };
                } else if (dy !== 0) {
                    const newY = this.y + dy * this.speed;
                    if (newY >= 0 && newY <= canvas.height - this.height) {
                        this.y = newY;
                    }
                    this.direction = { x: 0, y: dy };
                }
            }

            shoot() {
                if (this.shootCooldown <= 0) {
                    const bulletSpeed = 3;
                    const bullet = new Bullet(
                        this.x + this.width / 2,
                        this.y + (this.isEnemy ? this.height : 0),
                        this.direction.x * bulletSpeed,
                        this.direction.y * bulletSpeed,
                        this.color,
                        this.isEnemy
                    );
                    this.bullets.push(bullet);
                    this.shootCooldown = this.isEnemy ? 80 : 25;
                }
            }

            update(players) {
                if (this.shootCooldown > 0) {
                    this.shootCooldown--;
                }

                // 更新子弹
                this.bullets = this.bullets.filter(bullet => {
                    bullet.update();
                    return bullet.isActive();
                });

                if (this.isEnemy) {
                    // 选择最近的玩家作为目标
                    const nearestPlayer = players.reduce((nearest, player) => {
                        const distToThis = Math.sqrt(
                            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
                        );
                        const distToNearest = Math.sqrt(
                            Math.pow(this.x - nearest.x, 2) + Math.pow(this.y - nearest.y, 2)
                        );
                        return distToThis < distToNearest ? player : nearest;
                    });

                    const dx = nearestPlayer.x - this.x;
                    const dy = nearestPlayer.y - this.y;
                    const dist = Math.sqrt(dx * dx + dy * dy);

                    if (dist > 200) {
                        if (Math.abs(dy) > 50) {
                            this.moveInDirection(0, dy > 0 ? 1 : -1);
                        } else {
                            this.moveInDirection(dx > 0 ? 1 : -1, 0);
                        }
                    } else if (dist < 150) {
                        if (Math.abs(dx) > 50) {
                            this.moveInDirection(dx > 0 ? -1 : 1, 0);
                        } else {
                            this.moveInDirection(0, dy > 0 ? -1 : 1);
                        }
                    }

                    this.direction = {
                        x: dx / dist,
                        y: dy / dist
                    };

                    if (Math.random() < 0.02) {
                        this.shoot();
                    }
                } else {
                    // 玩家控制
                    const dx = (keys[this.controls.right] ? 1 : 0) - (keys[this.controls.left] ? 1 : 0);
                    const dy = (keys[this.controls.down] ? 1 : 0) - (keys[this.controls.up] ? 1 : 0);
                    this.moveInDirection(dx, dy);

                    if (keys[this.controls.shoot]) {
                        this.shoot();
                    }
                }
            }

            draw() {
                ctx.fillStyle = this.color;
                ctx.fillRect(this.x, this.y, this.width, this.height);

                ctx.beginPath();
                ctx.strokeStyle = 'white';
                ctx.lineWidth = 3;
                const gunLength = 20;
                ctx.moveTo(this.x + this.width/2, this.y + this.height/2);
                ctx.lineTo(
                    this.x + this.width/2 + this.direction.x * gunLength,
                    this.y + this.height/2 + this.direction.y * gunLength
                );
                ctx.stroke();
            }
        }

        class Bullet {
            constructor(x, y, dx, dy, tankColor, isEnemy) {
                this.x = x;
                this.y = y;
                this.dx = dx;
                this.dy = dy;
                this.width = 8;
                this.height = 8;
                this.tankColor = tankColor;
                this.isEnemy = isEnemy;
            }

            update() {
                this.x += this.dx;
                this.y += this.dy;
            }

            isActive() {
                return this.x >= 0 && this.x <= canvas.width &&
                       this.y >= 0 && this.y <= canvas.height;
            }

            draw() {
                ctx.fillStyle = this.isEnemy ? 'red' : (this.tankColor === 'blue' ? 'yellow' : 'lightgreen');
                ctx.fillRect(this.x - this.width/2, this.y - this.height/2, 
                           this.width, this.height);
            }
        }

        // 游戏状态
        let gameOver = false;
        let score = 0;
        const player1 = new Tank(canvas.width/3, canvas.height - 60, 'blue', {
            up: 'ArrowUp',
            down: 'ArrowDown',
            left: 'ArrowLeft',
            right: 'ArrowRight',
            shoot: 'Enter'
        });
        const player2 = new Tank(2 * canvas.width/3, canvas.height - 60, 'green', {
            up: 'w',
            down: 's',
            left: 'a',
            right: 'd',
            shoot: ' '
        });
        const enemies = [];
        const maxEnemies = 4;

        function spawnEnemy() {
            if (enemies.length < maxEnemies) {
                enemies.push(new Tank(
                    Math.random() * (canvas.width - 40),
                    50,
                    'red',
                    null,
                    true
                ));
            }
        }

        // 初始生成敌人
        for(let i = 0; i < 2; i++) {
            spawnEnemy();
        }

        // 键盘事件监听
        const keys = {};

        document.addEventListener('keydown', (e) => {
            if (gameOver) return;
            
            if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' ', 'w', 'a', 's', 'd', 'Enter'].includes(e.key)) {
                e.preventDefault();
            }
            
            keys[e.key] = true;
        });

        document.addEventListener('keyup', (e) => {
            keys[e.key] = false;
        });

        function checkCollisions() {
            const players = [player1, player2];
            const allPlayerBullets = [...player1.bullets, ...player2.bullets];

            // 检查玩家子弹是否击中敌人
            allPlayerBullets.forEach((bullet, bulletIndex) => {
                enemies.forEach((enemy, enemyIndex) => {
                    if (bullet.x > enemy.x && bullet.x < enemy.x + enemy.width &&
                        bullet.y > enemy.y && bullet.y < enemy.y + enemy.height) {
                        enemies.splice(enemyIndex, 1);
                        bullet.y = -10; // 移除子弹
                        score += 100;
                        document.getElementById('score').textContent = score;
                    }
                });
            });

            // 检查敌人子弹是否击中玩家
            enemies.forEach(enemy => {
                enemy.bullets.forEach((bullet, bulletIndex) => {
                    players.forEach(player => {
                        if (bullet.x > player.x && bullet.x < player.x + player.width &&
                            bullet.y > player.y && bullet.y < player.y + player.height) {
                            player.health -= 10;
                            enemy.bullets.splice(bulletIndex, 1);
                            document.getElementById(player === player1 ? 'health1' : 'health2').textContent = player.health;
                            if (player.health <= 0) {
                                gameOver = true;
                            }
                        }
                    });
                });
            });
        }

        function gameLoop() {
            if (gameOver) {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.fillStyle = 'white';
                ctx.font = '48px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('游戏结束!', canvas.width/2, canvas.height/2);
                ctx.font = '36px Arial';
                ctx.fillText(`最终得分: ${score}`, canvas.width/2, canvas.height/2 + 50);
                return;
            }

            // 清空画布
            ctx.fillStyle = 'black';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 更新和绘制玩家
            const players = [player1, player2];
            player1.update(players);
            player2.update(players);
            player1.draw();
            player2.draw();

            // 更新和绘制敌人
            enemies.forEach(enemy => {
                enemy.update(players);
                enemy.draw();
            });

            // 绘制所有子弹
            player1.bullets.forEach(bullet => bullet.draw());
            player2.bullets.forEach(bullet => bullet.draw());
            enemies.forEach(enemy => enemy.bullets.forEach(bullet => bullet.draw()));

            // 检查碰撞
            checkCollisions();

            // 生成新敌人
            if (Math.random() < 0.02) {
                spawnEnemy();
            }

            requestAnimationFrame(gameLoop);
        }

        gameLoop();
    </script>
</body>
</html>


